<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="源文件名称" prop="name" label-width="100">
              <el-input v-model="queryParams.name" placeholder="请输入源文件名称" clearable />
            </el-form-item>
            <el-form-item label="文件类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择" clearable @change="handleTypeChange">
                <el-option v-for="dict in fileTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="文件格式" prop="extension" label-width="100">
              <el-select v-model="queryParams.extension" placeholder="请选择" clearable>
                <el-option v-for="dict in inputModelTypes" :key="dict.value" :label="dict" :value="dict" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleOpenAddFileDialog">新增文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleOpenImportFileDialog">批量导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleExport">导出Excel</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleBatchDelete">批量删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="tableRef" v-loading="loading" :data="tableDatas" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="80" :index="indexMethod" />
        <el-table-column label="源文件名称" prop="name" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="文件格式" prop="extension" width="150" />
        <el-table-column label="文件类型" prop="type" width="150" />
        <el-table-column label="文件大小" prop="size" width="120">
          <template #default="scope">
            {{ getSizeStr(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" width="150" />
        <el-table-column label="创建时间" align="center" width="180" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="text" @click="handleDownloadSource(scope.row)">下载源文件</el-button>
            <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <AddFileDialog ref="addFileDialogRef" @call-back="getList" />
    <ImportFileDialog ref="importFileDialogRef" @call-back="getList" />
  </div>
</template>

<script setup name="ConversionRecordManagement" lang="ts">
import { optionType } from '@/api/caxDataConversionMajorComponent/type';
import { types } from '@/api/caxDataConversionMajorComponent/index';
import { sourceFileList, downloadSource, exportData, sourceFileDelete } from '@/api/caxDataConversionMajorComponent/fileManagement/index';
import AddFileDialog from './addFileDialog.vue';
import ImportFileDialog from './importFileDialog.vue';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const addFileDialogRef = ref<ElDialogInstance>();
const importFileDialogRef = ref<ElDialogInstance>();
const multipleSelection = ref([]);
const fileTypes = ref(types);
const inputModelTypes = ref([]);
const queryParams = reactive({
  name: '',
  extension: '',
  type: '',
  beginCreateTime: '',
  endCreateTime: '',
  pageNum: 1,
  pageSize: 10
});
const tableDatas = ref();
const handleTypeChange = () => {
  if (queryParams.type) {
    const obj = fileTypes.value.find((item) => item.value === queryParams.type);
    if (obj) {
      inputModelTypes.value = obj.inputType;
      return;
    }
  }
  let arr = [];
  fileTypes.value.forEach((element) => {
    arr = [...arr, ...element.inputType];
  });
  inputModelTypes.value = arr;
};
const getList = async () => {
  if (dateRange.value?.length) {
    queryParams.beginCreateTime = String(dateRange.value[0]);
    queryParams.endCreateTime = String(dateRange.value[1]);
  } else {
    queryParams.beginCreateTime = '';
    queryParams.endCreateTime = '';
  }
  loading.value = true;
  const res = await sourceFileList(queryParams);
  tableDatas.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
const getSizeStr = (size) => {
  if (size < 1024) {
    return size + 'B';
  } else if (size > 1023 && size < 1024 * 1024) {
    return Number(size / 1024).toFixed(2) + 'kB';
  } else {
    return Number(size / 1024 / 1024).toFixed(2) + 'MB';
  }
};
const indexMethod = (index) => {
  return (queryParams.pageNum - 1) * queryParams.pageSize + index + 1;
};
const handleOpenAddFileDialog = () => {
  addFileDialogRef.value.openDialog();
};
const handleOpenImportFileDialog = () => {
  importFileDialogRef.value.openDialog();
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const handleDownloadSource = (row) => {
  downloadSource(row.id).then((res) => {
    downloadFile(res, row.name);
  });
};
const handleDelete = async (id) => {
  await proxy?.$modal.confirm('是否确认删除选择数据！');
  await sourceFileDelete(id);
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};
const handleBatchDelete = async () => {
  const ids = multipleSelection.value.map((item) => item.id).join(',');
  if (!ids) {
    await proxy?.$modal.msgWarning('请选择要删除的数据！');
    return false;
  }
  await proxy?.$modal.confirm('是否确认删除选择数据！');
  await sourceFileDelete(ids);
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};
const handleExport = () => {
  const formData = new FormData();
  for (const key in queryParams) {
    formData.append(key, queryParams[key]);
  }
  exportData(formData).then((res) => {
    downloadFile(res, '源文件导出.xlsx');
  });
};
onMounted(() => {
  getList();
  handleTypeChange();
});
</script>
<style lang="scss" scoped></style>
